import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ExportDatabaseSchema {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/tworice_admin";
        String username = "root";
        String password = "123456";

        String databaseName = "tworice_admin";

        try {
            Connection connection = DriverManager.getConnection(url, username, password);

            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SHOW CREATE DATABASE " + databaseName);

            if (resultSet.next()) {
                String createDatabaseSQL = resultSet.getString(2);
                writeToFile(createDatabaseSQL, "database_schema.sql",true);
                System.out.println("Database schema exported successfully.");
            }

            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void writeToFile(String content, String filePath,boolean append) {
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(filePath,append));
            writer.write(content);
            writer.write(";");
            writer.newLine();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
